package com.xuz.step3;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpParser;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Request {
    static Pattern methodRegex = Pattern.compile("(GET|PUT|POST|DELETE|OPTIONS|TRACE|HEAD)");

    public String getBody() {
        return body;
    }

    public String getMethod() {
        return method;
    }

    public HashMap<String, String> getHeaders() {
        return headers;
    }

    private final String body;
    private final String method;
    private final HashMap<String, String> headers;

    public Request(Socket socket) throws IOException {
        // DataInputStream -> primitives(Char, Float)
        // InputStream -> bytes
        DataInputStream iptStream = new DataInputStream(socket.getInputStream());
        BufferedReader bfReader = new BufferedReader(new InputStreamReader(iptStream));

        // GET /path HTTP/1.1
        String methodLine = HttpParser.readLine(iptStream, "UTF-8");
        Matcher m = methodRegex.matcher(methodLine);
        m.find();
        String method = m.group();

        // Content-Type:xxxx
        // Length : xxx
        Header[] headers = HttpParser.parseHeaders(iptStream, "UTF-8");
        HashMap<String, String> headMap = new HashMap<>();
        for (Header h : headers) {
            headMap.put(h.getName(), h.getValue());
        }

        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(iptStream));
        StringBuilder body = new StringBuilder();
        char[] buffer = new char[1024];

        while (iptStream.available() > 0) {
            bufferReader.read(buffer);
            body.append(buffer);
        }

        this.body = body.toString();
        this.method = method;
        this.headers = headMap;

    }
}
